<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="JkExpertForm" ref="formRef">
          <a-row>
						<a-col :span="12">
							<a-form-item label="姓名" v-bind="validateInfos.realName" id="JkExpertForm-realName" name="realName">
								<a-input v-model:value="formData.realName" placeholder="请输入姓名"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="性别" v-bind="validateInfos.gender" id="JkExpertForm-gender" name="gender">
								<j-dict-select-tag type='radio' v-model:value="formData.gender" dictCode="sex" placeholder="请选择性别"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="头像" v-bind="validateInfos.personePhone" id="JkExpertForm-personePhone" name="personePhone">
								<j-image-upload :fileMax=1 v-model:value="formData.personePhone" ></j-image-upload>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="出生年月" v-bind="validateInfos.birthdate" id="JkExpertForm-birthdate" name="birthdate">
								<a-date-picker placeholder="请选择出生年月"  v-model:value="formData.birthdate" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="最高学历" v-bind="validateInfos.education" id="JkExpertForm-education" name="education">
								<j-dict-select-tag v-model:value="formData.education" dictCode="expert_xueli" placeholder="请选择最高学历"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="专业" v-bind="validateInfos.major" id="JkExpertForm-major" name="major">
								<a-input v-model:value="formData.major" placeholder="请输入专业"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="毕业院校" v-bind="validateInfos.graduationSchool" id="JkExpertForm-graduationSchool" name="graduationSchool">
								<a-input v-model:value="formData.graduationSchool" placeholder="请输入毕业院校"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="职称/头衔" v-bind="validateInfos.title" id="JkExpertForm-title" name="title">
								<a-input v-model:value="formData.title" placeholder="请输入职称/头衔"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="专业领域" v-bind="validateInfos.expertiseField" id="JkExpertForm-expertiseField" name="expertiseField">
								<j-tree-select
									dict="cms_domain_type,type_name,id"
									pidValue="0"
									
									v-model:value="formData.expertiseField"
									@change="(value) => handleFormChange('expertiseField', value)" allow-clear >
								</j-tree-select>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="所属机构" v-bind="validateInfos.organization" id="JkExpertForm-organization" name="organization">
								<a-input v-model:value="formData.organization" placeholder="请输入所属机构"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="联系电话" v-bind="validateInfos.contactPhone" id="JkExpertForm-contactPhone" name="contactPhone">
								<a-input v-model:value="formData.contactPhone" placeholder="请输入联系电话"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="电子邮箱" v-bind="validateInfos.contactEmail" id="JkExpertForm-contactEmail" name="contactEmail">
								<a-input v-model:value="formData.contactEmail" placeholder="请输入电子邮箱"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="认证状态" v-bind="validateInfos.isVerified" id="JkExpertForm-isVerified" name="isVerified">
								<j-dict-select-tag type='radio' v-model:value="formData.isVerified" dictCode="expert_renz_status" placeholder="请选择认证状态"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="状态" v-bind="validateInfos.zjStatus" id="JkExpertForm-zjStatus" name="zjStatus">
								<j-dict-select-tag type='radio' v-model:value="formData.zjStatus" dictCode="expert_status" placeholder="请选择状态"  allow-clear />
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated style="overflow:hidden;">
      <a-tab-pane class="sub-one-form" tab="专家工作经历" key="jkExpertWork" :forceRender="true">
        <jk-expert-work-form ref="jkExpertWorkFormRef" :disabled="disabled"></jk-expert-work-form>
      </a-tab-pane>
      <a-tab-pane class="sub-one-form" tab="专家学术成果" key="jkExpertAcademic" :forceRender="true">
        <jk-expert-academic-form ref="jkExpertAcademicFormRef" :disabled="disabled"></jk-expert-academic-form>
      </a-tab-pane>
      <a-tab-pane class="sub-one-form" tab="专家个人简介" key="jkExpertProfile" :forceRender="true">
        <jk-expert-profile-form ref="jkExpertProfileFormRef" :disabled="disabled"></jk-expert-profile-form>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryDataById, saveOrUpdate } from '../JkExpert.api';
  import JkExpertWorkForm from './JkExpertWorkForm.vue'
  import JkExpertAcademicForm from './JkExpertAcademicForm.vue'
  import JkExpertProfileForm from './JkExpertProfileForm.vue'
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JTreeSelect from '/@/components/Form/src/jeecg/components/JTreeSelect.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "JkExpertForm",
    components:{
      JDictSelectTag,
      JTreeSelect,
      JImageUpload,
			JFormContainer,
      JkExpertWorkForm,
      JkExpertAcademicForm,
      JkExpertProfileForm,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const formRef = ref();
      const jkExpertWorkFormRef = ref();
      const jkExpertAcademicFormRef = ref();
      const jkExpertProfileFormRef = ref();
      const activeKey = ref('jkExpertWork');
      const formData = reactive<Record<string, any>>({
        id: '',
        realName: '',   
        gender: '',
        personePhone: '',   
        birthdate: '',   
        education: '',   
        major: '',   
        graduationSchool: '',   
        title: '',   
        expertiseField: '',   
        organization: '',   
        contactPhone: '',   
        contactEmail: '',   
        isVerified: '',   
        zjStatus: '',   
      });

      //表单验证
      const validatorRules = reactive({
        contactPhone: [{ required: false}, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!'},],
        contactEmail: [{ required: false}, { pattern: /^([\w]+\.*)([\w]+)@[\w]+\.\w{3}(\.\w{2}|)$/, message: '请输入正确的电子邮件!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      

      function add() {
        resetFields();
        jkExpertWorkFormRef.value.initFormData();
        jkExpertAcademicFormRef.value.initFormData();
        jkExpertProfileFormRef.value.initFormData();
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        await jkExpertWorkFormRef.value.initFormData(row['id']);
        await jkExpertAcademicFormRef.value.initFormData(row['id']);
        await jkExpertProfileFormRef.value.initFormData(row['id']);
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'jkExpertWork': jkExpertWorkFormRef,
        'jkExpertAcademic': jkExpertAcademicFormRef,
        'jkExpertProfile': jkExpertProfileFormRef,
      });

      async function getFormData() {
        try {
          // 触发表单验证
          await validate();
        } catch ({ errorFields }) {
          if (errorFields) {
            const firstField = errorFields[0];
            if (firstField) {
              formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
            }
          }
          return Promise.reject(errorFields);
        }
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }


      return {
        jkExpertWorkFormRef,
        jkExpertAcademicFormRef,
        jkExpertProfileFormRef,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
      }
    }
  });
</script>
<style lang="less" scoped>
  .ant-tabs-tabpane.sub-one-form {
    max-height: 340px;
    overflow: auto;
  }
</style>
